const path = require("path");
const { VueLoaderPlugin } = require("vue-loader");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const glob = require("glob");

const entryObj = {};
const htmlWebpackPluginList = [];

const entryList = glob.sync(path.resolve(process.cwd(), "./app/pages/**/entry.**.js"));
entryList.forEach((entry) => {
  const entryName = path.basename(entry, path.extname(entry));
  entryObj[entryName] = entry;

  htmlWebpackPluginList.push(
    new HtmlWebpackPlugin({
      template: path.resolve(process.cwd(), './app/views/entry.tpl'),
      filename: path.resolve(
        process.cwd(),
        "./app/public/dist/",
        `${entryName}.tpl`
      ),
      chunks: [entryName],
    })
  );
});

module.exports = {
  entry: entryObj,
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: "vue-loader",
      },
      {
        test: /\.less$/,
        use: ["style-loader", "css-loader", "less-loader"],
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.js$/,
        include: [path.resolve(process.cwd(), "./app/pages")],
        use: ["babel-loader"],
      },
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: "url-loader",
            options: {
              limit: 300,
              esModule: false,
            },
          },
        ],
      },
      {
        test: /\.(eot|ttf|woff|woff2|svg)$/,
        use: "file-loader",
      },
    ],
  },
  output: {
    
  },
  resolve: {
    extensions: [".js", ".vue", ".less", ".css"],
    alias: {
      $pages: path.resolve(process.cwd(), "./app/pages"),
      $common: path.resolve(process.cwd(), "./app/pages/common"),
      $widget: path.resolve(process.cwd(), "./app/pages/widgets"),
      $store: path.resolve(process.cwd(), "./app/pages/store"),
    },
  },
  plugins: [
    new VueLoaderPlugin(),
    new webpack.ProvidePlugin({
      Vue: "vue",
      axios: "axios",
      '_': 'lodash',
    }),
    new webpack.DefinePlugin({
      __VUE_OPTIONS_API__: true,
      __VUE_PROD_DEVTOOLS__: false,
      __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: false,
    }),
    ...htmlWebpackPluginList,
  ],
  optimization: {
    splitChunks: {
      chunks: 'all',
      maxAsyncRequests: 10,
      maxInitialRequests: 10,
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          priority: -10,
          reuseExistingChunk: true,
          enforce: true,
        },
        common: {
          test: /[\\/]common|widgets[\\/]/,
          name: 'common',
          minChunks: 2,
          minSize: 1,
          priority: -20,
          reuseExistingChunk: true,
        },
      },
    },
    runtimeChunk: {
      name: 'runtime',
    },
  },
};
